import { request } from "../request";

/**
 * 通过URL上传文件接口返回结构
 */
export interface UploadFileByUrlRes {
    code: number;
    message: string;
    data: Record<string, unknown>;
    timestamp: Record<string, unknown>;
}

/**
 * 通过文件URL上传文件到OSS（使用POST body，推荐）
 * @param fileUrl 文件URL
 * @param folder 上传到的文件夹（可选）
 * @returns 上传结果
 */
export function uploadFileByUrlAPI(fileUrl: string, folder?: string): Promise<UploadFileByUrlRes> {
    const token = localStorage.getItem("token") || "";

    const requestBody: { fileUrl: string; folder?: string } = { fileUrl };
    if (folder) {
        requestBody.folder = folder;
    }

    return request("api/file/upload/by-url-body", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            'Authorization': `Bearer ${token}`
        },
        data: JSON.stringify(requestBody)
    });
}

/**
 * 通过文件URL上传文件到OSS（使用URL编码，备用方案）
 * @param fileUrl 文件URL
 * @param folder 上传到的文件夹（可选）
 * @returns 上传结果
 */
export function uploadFileByUrlWithEncodingAPI(fileUrl: string, folder?: string): Promise<UploadFileByUrlRes> {
    const token = localStorage.getItem("token") || "";

    // 对整个URL进行编码
    const encodedFileUrl = encodeURIComponent(fileUrl);
    let url = `api/file/upload/by-url?fileUrl=${encodedFileUrl}`;

    if (folder) {
        url += `&folder=${encodeURIComponent(folder)}`;
    }

    return request(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            'Authorization': `Bearer ${token}`
        },
    });
}